<template>
  <div>
    <article class="main-breadcrumb">
      <el-breadcrumb separator="/" class="main-breadcrumb-wrap">
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">考场管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">考场工位</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </article>
    <div class="nx-content">
      <div class="flex-bet">
        <div class="left-title flex"></div>
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">

          <el-form-item label="">
            <el-button-group>
              <el-button :class="{ active: drawType == 'polygon' }" @click="drawPolygon()">开始绘制</el-button>

              <el-button @click="clearCanvas">还原地图</el-button>
            </el-button-group>
          </el-form-item>

        </el-form>
      </div>
      <div class="content" id="content">
        <canvas id="canvas" :width="width" :height="height"></canvas>
        <div v-show="dots !== []" class="point" v-for="(item, index) in dots" :key="index" :style="{ position: 'absolute', top: item.ycoordinate + 'px', left: item.xcoordinate + 'px' }" @click="handlerTipShow(index)">
          <div v-show="dots[index].tipShow" class="tip">
            <div class="tip_input">
              <img class="delImg" @click="cancel" src="../../../assets/del.png" alt="">
              <el-input class="input_ top" v-model="dots[index].name" placeholder="请输入工位名称" clearable maxlength="50" show-word-limit :disabled="seeType"></el-input>
              <el-input class="input_" v-model="dots[index].code" placeholder="请输入工位编码" clearable maxlength="50" show-word-limit :disabled="seeType"></el-input>
              <div style="display:flex;justify-content: space-around;">

                <el-button class="input_" @click="saveSet">确认</el-button>
                <el-button class="input_" @click="delSet">删除</el-button>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getExaminationRoomSeatList, saveExaminationRoomSeat, delExaminationRoomSeat } from '@/api/school'

export default {
  components: {},
  data() {
    return {
      // 查询字段
      searchForm: {
        mapId: '',
        examinationRoomId: '1'
      },
      // 表格字段
      tableCols: [
        {
          label: '绘制区域',
          prop: 'name',
          align: 'center'
        },
        {
          label: '区域类型',
          slot: 'type',
          align: 'center'
        },
        {
          label: '是否开启报警',
          slot: 'isAlarm',
          align: 'center'
        }
      ],
      showMarker: false,
      oldDots: [], //
      setJsonDots: [], //
      videoIdArray: [], //摄像头
      mapImage: '', // 标注图片
      locationMapSetVideoList: [],
      locationMapSets: [], //	定位地图标记
      addEditIsDialog_c: false, // 弹窗是否显示
      seeType: false, // 是否禁用
      monitorArray: [], // 摄像头集合
      addEditIsDialog: false, // 添加编辑页面状态
      addEditStatus: 'add',
      addEditId: '', // 添加编辑rowid
      schoolArray: [], // 考场集合
      mapArray: [], // 地图集合
      width: '',
      height: '',
      rect: [],
      canvas: {},
      showMenu: false,
      x: '',
      y: '',
      canvasObjects: [],
      dots: [], // 摄像头点位
      areaDots: [], // 区域
      imgClientWidth: 0, // 图片宽度
      imgClientHeight: 0, // 图片高度
      tipShow: true,

      activeIndex: -1,
      mouseFrom: {},
      mouseTo: {},
      drawType: null, //当前绘制图像的种类
      canvasObjectIndex: 0,
      textbox: null,
      rectangleLabel: 'warning',
      drawWidth: 2, //笔触宽度
      color: '#E34F51', //画笔颜色
      drawingObject: null, //当前绘制对象
      moveCount: 1, //绘制移动计数器
      doDrawing: false, // 绘制状态

      //polygon 相关参数
      polygonMode: false,
      pointArray: [],
      lineArray: [],
      activeShape: false,
      activeLine: '',
      line: {},
      xyShow: false,
      tipShowindex: ''
    }
  },
  mounted() {
    // 查询
    this.getList()
  },
  watch: {
    drawType() {
      this.canvas.selection = !this.drawType
    },
    width() {
      this.canvas.setWidth(this.width)
    },
    height() {
      this.canvas.setHeight(this.height)
    }
  },
  methods: {
    // 鼠标按下时触发
    mousedown(e) {
      // 记录鼠标按下时的坐标
      var xy = e.pointer || this.transformMouse(e.e.offsetX, e.e.offsetY)
      if (this.xyShow == true) {
        this.dots.push({
          xcoordinate: xy.x,
          ycoordinate: xy.y,
          tipShow: true,
          examinationRoomId: this.$route.query.row.id
        })
      }
      console.log(22)
    },
    // 鼠标松开执行
    mouseup(e) {
      var xy = e.pointer || this.transformMouse(e.e.offsetX, e.e.offsetY)
      this.mouseTo.x = xy.x
      this.mouseTo.y = xy.y
      this.drawingObject = null
      this.moveCount = 1
      if (this.drawType != 'polygon') {
        this.doDrawing = false
      }
    },
    drawPolygon() {
      this.drawType = 'polygon'
      this.polygonMode = true
      this.isShow = false
      this.xyShow = true
      this.canvas.isDrawingMode = false
    },
    // 查询列表
    getList() {
      console.log(this.$route.query.row)
      getExaminationRoomSeatList({ examinationRoomId: this.$route.query.row.id }).then((res) => {
        if (res.code == 200) {
          this.dots = res.data
          this.$nextTick(() => {
            this.loadBacImg()
          })
        }
      })
    },
    // 获取背景图
    getImage() {
      this.loadBacImg()
      this.getList()
    },

    // 区域
    zonelog() {
      this.getJson()
    },
    // 提交
    saveSet() {
      saveExaminationRoomSeat(this.dots[this.tipShowindex]).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          setTimeout(() => {
            this.dots[this.tipShowindex].tipShow = false
            this.getImage()
          }, 300)
        }
      })
      this.isShow = false
    },
    delSet() {
      if (this.dots[this.tipShowindex].id) {
        delExaminationRoomSeat({ id: this.dots[this.tipShowindex].id }).then((res) => {
          if (res.code == 200) {
            if (res.code == 200) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              setTimeout(() => {
                this.dots[this.tipShowindex].tipShow = false
                this.getImage()
              }, 300)
            }
          }
        })
      } else {
        this.$message({
          message: '请先保存考场工位',
          type: 'warning'
        })
      }
    },
    //渲染背景图片至canvas
    loadBacImg() {
      let img = `${this.$route.query.row.image}`
      var imgObj = new Image()
      imgObj.src = img
      let that = this
      imgObj.onload = function () {
        that.imgClientWidth = imgObj.width
        that.imgClientHeight = imgObj.height
        setTimeout(() => {
          that.canvas.setBackgroundImage(img, that.canvas.renderAll.bind(that.canvas), {
            scaleX: that.width / imgObj.width, //计算出图片要拉伸的宽度
            scaleY: that.height / imgObj.height //计算出图片要拉伸的高度
          })
        }, 100)

        that.init()
        that.getDots()
      }
    },
    getDots() {
      this.oldDots.forEach((val) => {
        this.dots.push({
          coordinate: { x: (val.coordinate.x / 100) * this.width, y: this.height - (val.coordinate.y / 100) * this.height },
          videoId: val.videoId
        })
      })
    },
    // 定位tip
    handlerTipShow(index) {
      this.$forceUpdate()
      this.dots[index].tipShow = true
      this.tipShowindex = index
    },
    getIndex(index) {},
    cancel() {
      setTimeout(() => {
        this.dots[this.tipShowindex].tipShow = false
        this.$forceUpdate()
      }, 100)
    },
    // 初始化
    init() {
      this.canvas = new fabric.Canvas('canvas', {
        skipTargetFind: false, //当为真时，跳过目标检测。目标检测将返回始终未定义。点击选择将无效
        selectable: false, //为false时，不能选择对象进行修改
        // selection: false   // 是否可以多个对象为一组
        fireRightClick: true, // 启用右键，button的数字为3
        stopContextMenu: true // 禁止默认右键菜单
      })
      const boxDOM = document.getElementById('content')
      this.width = boxDOM.offsetWidth
      this.height = boxDOM.offsetWidth / (this.imgClientWidth / this.imgClientHeight)
      this.canvas.setWidth(this.width)
      this.canvas.setHeight(this.height)
      this.canvas.renderAll()

      this.canvas.selectionColor = 'rgba(0,0,0,0.05)'
      this.canvas.on('mouse:down', this.mousedown)
      this.canvas.on('mouse:move', this.mousemove)
      this.canvas.on('mouse:up', this.mouseup)

      document.onkeydown = (e) => {
        // 键盘 delect删除所选元素
        if (e.keyCode == 46) {
          this.deleteObj()
        }
        // ctrl+z 删除最近添加的元素
        if (e.keyCode == 90 && e.ctrlKey) {
          this.canvas.remove(this.canvas.getObjects()[this.canvas.getObjects().length - 1])
        }
      }

      this.getP()
    },
    // 初始化区域
    getP() {
      this.setJsonDots.forEach((item) => {
        let setJsonString = []
        item.setJsonString.forEach((val) => {
          setJsonString.push({
            x: (val.x / 100) * this.width,
            y: this.height - (val.y / 100) * this.height
          })
        })
        var polygon = new fabric.Polygon(setJsonString, {
          stroke: item.color,
          strokeWidth: this.drawWidth,
          fill: 'rgba(43,100,206,0.6)',
          opacity: 1,
          hasBorders: false,
          hasControls: false,
          lockMovementX: true,
          lockMovementY: true,
          evented: false
        })
        this.canvas.add(polygon)
        this.canvas.renderAll()
      })
      this.canvas.renderAll()
    },
    // 开始绘制时，指定绘画种类
    drawTypeChange(e) {
      this.drawType = e
      this.canvas.skipTargetFind = !!e
      if (e == 'pen') {
        // isDrawingMode为true 才可以自由绘画
        this.canvas.isDrawingMode = true
      } else {
        this.canvas.isDrawingMode = false
      }
    },
    // 摄像头
    handleShow() {
      this.isShow = true
    },

    // 还原
    clearCanvas() {
      ;(this.isShow = false), (this.mouseFrom = {}), (this.mouseTo = {}), (this.drawType = null), (this.canvasObjectIndex = 0), (this.rectangleLabel = 'warning'), (this.drawWidth = 2), (this.color = '#E34F51'), (this.drawingObject = null), (this.moveCount = 1), (this.doDrawing = false), (this.polygonMode = false), (this.pointArray = []), (this.lineArray = []), (this.activeShape = false), (this.activeLine = ''), (this.line = {}), (this.dots = [])
      this.setJsonDots = []
      this.areaDots = []
      this.oldDots = []
      this.isShow = false
      this.canvas.dispose()
      this.getImage()
    }
  }
}
</script>

<style lang="less" scoped>
.main-breadcrumb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 76px;
  border-bottom: solid 20px #f2f2f2;
  padding-left: 20px;
  .main-breadcrumb-wrap {
    font-size: 16px;
    line-height: 68px;
    .main-breadcrumb-home {
      cursor: pointer;
      color: #666666;
      font-weight: bold;
    }
    .main-breadcrumb-sp {
      color: #666666;
      font-weight: bold;
    }
  }
}
.content {
  width: 100%;
  // height: 80.19vh;
  margin: 0 auto;
  position: relative;
  .area-box {
    width: 90px;
  }
  .point {
    width: 18px;
    height: 25px;
    background: url(../../../assets/point.png) center center;
    background-size: 100% 100%;
    margin-left: -8px;
    margin-top: -20px;
    background-repeat: no-repeat;
    cursor: pointer;
    .tip {
      width: 205px;
      height: 180px;
      border-radius: 5%;
      position: absolute;
      top: -200%;
      left: 200%;
      background-color: #f1f0f0;
      box-shadow: 1em 1em 1em rgb(195, 196, 194);
      font-size: 10px;
      color: white;

      display: flex;
      flex-direction: column;

      justify-content: space-around;
      // padding: 0 0px 3px 5px;
      .tip_input {
        width: 180px;
        margin: 10px;
      }
      .input_ {
        margin: 5px;
      }
      .top {
        margin-top: 22px;
      }
    }
  }
  canvas {
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    left: 0;
    top: 0;
  }
}

.draw-btn-group {
  // width: 1270px;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  & > div {
    background: #fafafa;
    cursor: pointer;
    &:hover {
      background: #eee;
    }
  }
  .active {
    background: #eee;
  }
}
.delImg {
  width: 13px;
  position: absolute;
  right: 6px;
  top: 7px;
}
</style>
